package cn.wowjoy.commonlibrary.utils;


import android.util.Log;

import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleUnnotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.UUID;

import cn.wowjoy.commonlibrary.app.BaseApplication;

import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;

public class BLEUtils {
    private static BluetoothClient mClient;

    public static BluetoothClient getInstance() {
        if (mClient == null)
            mClient = new BluetoothClient(BaseApplication.getInstance());
        return mClient;
    }

    public static void openNotify(String mac, String suuid, String nuuid) {
        getInstance().notify(mac, UUID.fromString(suuid), UUID.fromString(nuuid), new BleNotifyResponse() {
            @Override
            public void onNotify(UUID service, UUID character, byte[] value) {
                String rep = HexUtils.bytesToHex(value);
                LiveEventBus.get().with("onNotify").post(rep);
            }

            @Override
            public void onResponse(int code) {
                if (code == REQUEST_SUCCESS) {
                    LiveEventBus.get().with("onNotify").post(mac);
                }
            }
        });
    }

    public static void writePsw(String mac, String s, String appendString, String suuid, String wuuid) {
        byte[] pswB = HexUtils.hexStringToBytes(s);
        final byte[] sum = {(byte) 0x00};
        for (int i = 0; i < pswB.length; i++) {
            sum[0] += pswB[i];
        }
        String all = s + HexUtils.bytesToHex(sum) + appendString;
        getInstance().write(mac, UUID.fromString(suuid), UUID.fromString(wuuid), HexUtils.hexStringToBytes(all), new BleWriteResponse() {
            @Override
            public void onResponse(int code) {
//                Log.e("write comm onResponse", all + "  " + code);
            }
        });
    }

    public static void closeNotify(String mac, String suuid, String nuuid) {
        getInstance().unnotify(mac, UUID.fromString(suuid), UUID.fromString(nuuid), new BleUnnotifyResponse() {
            @Override
            public void onResponse(int code) {
                Log.e("unnotify", "" + code);
                if (code == REQUEST_SUCCESS) {
                    getInstance().disconnect(mac);
                }
            }
        });
    }
}
